package fg.animation;

import java.util.ArrayList;

public class AnimationSequence {

	private int time = 0;
	private ArrayList<Animation> animations;
	private int index = 0;
	private Animation currentAnimation;
	private boolean active;
	private boolean looping;

	public AnimationSequence() {
		animations = new ArrayList<Animation>();
		active = false;
		looping = false;
	}

	public Animation getCurrentAnimation() {
		return currentAnimation;
	}

	public void add(Animation animation) {
		animations.add(animation);
		if (currentAnimation == null) {
			currentAnimation = animation;
			index = 0;
		}
	}

	public void removeAnimation(Animation animation) {
		animations.remove(animation);
	}
	
	public void update(int delta) {
		if (!active)
			return;
		
		if (null != currentAnimation) {
			time += delta;
			boolean running = currentAnimation.continueAnimation(time);
			if (!running) {
				time = 0;
				boolean isDone = (index + 1 >= animations.size());
				if (isDone) {
					if (looping) {
						restart();
					} else {
						active = false;
					}
				} else {
					index += 1;
					currentAnimation = animations.get(index);
				}
			}// if (!running)
		}// if (currentAnimation)
	}

	public void restart() {
		for (Animation a : animations) {
			a.reset();
		}
		
		if (!animations.isEmpty()) {
			currentAnimation = animations.get(0);
			index = 0;
		}

		time = 0;
	}

	public void clear() {
		animations.clear();
		currentAnimation = null;
		index = 0;
		active = false;
		restart();
	}

	/**
	 * @return the active
	 */
	public boolean isActive() {
		return active;
	}

	/**
	 * @param active
	 *            the active to set
	 */
	public void setActive(boolean active) {
		this.active = active;
	}

	/**
	 * @return the looping
	 */
	public boolean isLooping() {
		return looping;
	}

	/**
	 * @param looping
	 *            the looping to set
	 */
	public void setLooping(boolean looping) {
		this.looping = looping;
	}

}
